#include "stdafx.h"
#include "nSystem.h"

namespace ne{

std::ofstream System::m_logfile;
std::string System::m_filename;

void System::Notify(const std::string& message, const std::string& caption) {
#ifdef _WIN32
	MessageBoxA(NULL, message.c_str(), caption.c_str(), MB_OK | MB_ICONEXCLAMATION);
#endif
}

void System::Break() {
	__debugbreak();
}

void System::SetLogFile(const std::string& filename, const std::string& extension) {
	m_filename = filename + "." + extension;
}

void System::Msg(const std::string& message) {
	std::cout << message << std::endl;
}

unsigned int System::FileSize(const std::string& filename){
	FILE* file = nullptr;
	fopen_s(&file,filename.c_str(),"rb");
	if (file == nullptr){
		return 0;
	}
	fseek(file,0,SEEK_END);
	unsigned int size = ftell(file);
	//rewind(file); // we can return the pointer to the end if we want to re-use our FILE* 
	fclose(file);
	return size;
}

bool System::FileRead(const std::string& filename, void* buffer, int& size){
	FILE* file = nullptr;
	fopen_s(&file,filename.c_str(),"rb");
	if (file == nullptr){
		return false;
	}
	size = fread(buffer,1,size,file);
	fclose(file);
	return true;
}

bool System::FileSave(const std::string& filename, void* buffer, int& size){
	FILE* file = nullptr;
	fopen_s(&file, filename.c_str(), "wb");
	if (file == nullptr){
		return false;
	}
	size=fwrite(buffer,size,1,file);
	fclose(file);
	return true;
}

void System::Log(const std::string& message) {
	m_logfile.open(m_filename, std::ios::app);
	struct tm time;
	__time32_t long_time;
	_time32(&long_time);
	_localtime32_s(&time, &long_time);

	std::string line;
	line.append("[" + Convert::NumberToString(time.tm_year - 100));
	line.append("-" + Convert::NumberToString(time.tm_mon + 1));
	line.append("-" + Convert::NumberToString(time.tm_mday));
	line.append("_" + Convert::NumberToString(time.tm_hour));
	line.append(":" + Convert::NumberToString(time.tm_min));
	line.append(":" + Convert::NumberToString(time.tm_sec));
	m_logfile << line << "] " << message << std::endl;
#ifdef _DEBUG
	std::cout << message << std::endl;
#endif
	m_logfile.close();
}

}